import { reqCatesList, reqCateGoodsList } from "../../http/api";
//初始值
const initState = {
  catelist: [],
  goodslist: [],
};

//action types
const types = {
  CHANGE_GOODS_LISTS: "CHANGE_GOODS_LISTS",
  CHANGE_CATE_LIST: "CHANGE_CATE_LIST",
};

//action creator
export const actions = {
  //改变catelist
  changeCate: (catelist) => ({
    type: types.CHANGE_CATE_LIST,
    catelist,
  }),
  //获取数据
  reqcate: () => {
    return (dispatch, getState) => {
      reqCatesList().then((res) => {
        if (res.data.code === 200) {
          dispatch(actions.changeCate(res.data.list ? res.data.list : []));
          reqCateGoodsList({ fid:res.data.list[0].id}).then((res) => {
            if (res.data.code === 200) {
              dispatch(actions.changeGoods(res.data.list ? res.data.list : []));
            }
          });
        }
      });
    };
  },
  //改变goods
  changeGoods: (goodslist)            => ({
    type: types.CHANGE_GOODS_LISTS,
    goodslist,
  }),
  //获取数据
  reqgoods: (index) => {
    return (dispatch, getState) => {
        reqCateGoodsList({ fid:index}).then((res) => {
          if (res.data.code === 200) {
            dispatch(actions.changeGoods(res.data.list ? res.data.list : []));
          }
        });
    };
  },
};

//reducer
export const cateReducer = (state = initState, action) => {
  switch (action.type) {
    case types.CHANGE_GOODS_LISTS:
      return {
        ...state,
        goodslist: action.goodslist,
      };
    case types.CHANGE_CATE_LIST:
      return {
        ...state,
        catelist: action.catelist,
      };
    default:
      return state;
  }
};

//导出数据

export const getCate = (state) => state.cate.catelist;
export const getGoods = (state) => state.cate.goodslist;
